import React, { useEffect, useRef, useState } from 'react';

function WebMcpClient() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isConnected, setIsConnected] = useState(false);
  const [isProcessing, setIsProcessing] = useState(false);
  const [status, setStatus] = useState('正在连接...');
  const wsRef = useRef(null);
  const chatContainerRef = useRef(null);

  // 连接 WebSocket
  useEffect(() => {
    // 获取 WebSocket 服务器地址
    const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
    const wsUrl = `${protocol}//${window.location.host}/ws`;
    
    wsRef.current = new WebSocket(wsUrl);
    
    wsRef.current.onopen = () => {
      console.log('WebSocket 连接已建立');
      setIsConnected(true);
      setStatus('已连接，等待初始化...');
    };
    
    wsRef.current.onmessage = (event) => {
      try {
        const data = JSON.parse(event.data);
        handleServerMessage(data);
      } catch (error) {
        console.error('解析消息错误:', error);
      }
    };
    
    wsRef.current.onclose = () => {
      console.log('WebSocket 连接已关闭');
      setIsConnected(false);
      setStatus('连接已断开');
    };
    
    wsRef.current.onerror = (error) => {
      console.error('WebSocket 错误:', error);
      setStatus('连接错误');
    };
    
    return () => {
      if (wsRef.current) {
        wsRef.current.close();
      }
    };
  }, []);

  // 消息更新后自动滚动到底部
  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop = chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  // 处理从服务器接收的消息
  const handleServerMessage = (data) => {
    switch (data.type) {
      case 'init_success':
        setStatus('准备就绪');
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `✅ 系统已初始化，已加载 ${data.tools.length} 个工具`
        }]);
        break;
        
      case 'init_error':
        setStatus(`初始化失败: ${data.message}`);
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `❌ 初始化失败: ${data.message}`
        }]);
        break;
        
      case 'ai_thinking':
        // 这里可以显示 AI 在思考中
        break;
        
      case 'ai_response':
        setIsProcessing(false);
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'ai',
          content: data.content
        }]);
        break;
        
      case 'tool_call':
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'tool-call',
          toolName: data.name,
          arguments: data.arguments
        }]);
        break;
        
      case 'tool_result':
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'tool-result',
          toolName: data.name,
          result: data.result
        }]);
        break;
        
      case 'command_result':
        handleCommandResult(data);
        break;
        
      case 'error':
        setIsProcessing(false);
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `❌ 错误: ${data.message}`
        }]);
        break;
        
      default:
        console.log('收到未知类型消息:', data);
    }
  };

  // 处理命令结果
  const handleCommandResult = (data) => {
    setIsProcessing(false);
    
    switch (data.command) {
      case 'tools':
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `
🛠️ 可用工具:
${data.data.map(tool => `• ${tool.function.name} - ${tool.function.description}`).join('\n')}
          `
        }]);
        break;
        
      case 'servers':
        setMessages(prev => [...prev, {
          id: Date.now(),
          type: 'system',
          content: `
🖥️ 服务器状态:
${data.data.map(server => {
  const status = server.connected ? '✅ 已连接' : '❌ 未连接';
  return `• ${server.name} ${status} - ${server.description}`;
}).join('\n')}
          `
        }]);
        break;
        
      case 'model':
        if (data.success !== undefined) {
          const content = data.success 
            ? `✅ 已切换到模型: ${data.model}`
            : `❌ 未知模型: ${data.model}`;
            
          setMessages(prev => [...prev, {
            id: Date.now(),
            type: 'system',
            content
          }]);
        } else {
          setMessages(prev => [...prev, {
            id: Date.now(),
            type: 'system',
            content: `🤖 当前模型: ${data.data.currentModel}`
          }]);
        }
        break;
    }
  };

  // 发送消息
  const sendMessage = () => {
    if (!input.trim() || !isConnected || isProcessing) return;
    
    const message = input.trim();
    setInput('');
    setIsProcessing(true);
    
    // 添加用户消息到界面
    setMessages(prev => [...prev, {
      id: Date.now(),
      type: 'user',
      content: message
    }]);
    
    // 处理命令
    if (message.startsWith('/')) {
      wsRef.current.send(JSON.stringify({
        type: 'command',
        command: message
      }));
    } else {
      // 发送用户消息
      wsRef.current.send(JSON.stringify({
        type: 'user_message',
        content: message
      }));
    }
  };

  // 按下回车键发送消息
  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendMessage();
    }
  };

  // 渲染命令按钮
  const renderCommandButtons = () => {
    const commands = [
      { label: '帮助', command: '/help' },
      { label: '工具', command: '/tools' },
      { label: '服务器', command: '/servers' },
      { label: '清空', command: '/clear' }
    ];
    
    return (
      <div className="command-buttons">
        {commands.map((cmd, index) => (
          <button 
            key={index} 
            className="command-button"
            onClick={() => {
              setInput(cmd.command);
              setTimeout(sendMessage, 100); // 延迟执行以确保状态更新
            }}
            disabled={!isConnected || isProcessing}
          >
            {cmd.label}
          </button>
        ))}
      </div>
    );
  };

  // 渲染消息
  const renderMessages = () => {
    return messages.map(message => {
      if (message.type === 'system') {
        return (
          <div key={message.id} className="system-message">
            {message.content}
          </div>
        );
      } else if (message.type === 'tool-call') {
        return (
          <div key={message.id} className="tool-message">
            <div className="tool-name">🔧 工具调用: {message.toolName}</div>
            <pre className="tool-arguments">{message.arguments}</pre>
          </div>
        );
      } else if (message.type === 'tool-result') {
        return (
          <div key={message.id} className="tool-message">
            <div className="tool-name">🔄 工具结果: {message.toolName}</div>
            <pre className="tool-result">{message.result}</pre>
          </div>
        );
      } else {
        const messageClass = `message ${message.type === 'user' ? 'user-message' : 'ai-message'}`;
        
        return (
          <div key={message.id} className={messageClass}>
            {message.content}
          </div>
        );
      }
    });
  };

  return (
    <div className="container">
      <div className="header">
        <h1>MCP 客户端</h1>
        <div>{status}</div>
      </div>
      
      <div className="chat-container" ref={chatContainerRef}>
        {renderMessages()}
      </div>
      
      {renderCommandButtons()}
      
      <div className="input-container">
        <textarea
          className="input-field"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyPress={handleKeyPress}
          placeholder="输入消息或命令..."
          disabled={!isConnected || isProcessing}
          rows={2}
        />
        <button
          className="send-button"
          onClick={sendMessage}
          disabled={!input.trim() || !isConnected || isProcessing}
        >
          {isProcessing ? (
            <div className="loading-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          ) : '发送'}
        </button>
      </div>
    </div>
  );
}

export default WebMcpClient; 